
function ini() {
	
	// checkboxes with the client spoken languages 
	var langInputs = $('#clientLanguages li input');
	
	// pt and en are check by default 
	langInputs.parent().find('input[value=pt],[value=en]').attr('checked','checked');
	
}




/**
 * create and handle button events
 * @param offerId
 * @param classId
 * @param userId
 * @param schoolId
 */
function buttonEvents(offerId, classId, userId, schoolId) {

	var rightButton = $('#rightButton'); 
	rightButton.button();
	
	var leftButton = $('#leftButton'); 
	leftButton.button();
	
	var loadButton = $('#loadButton'); 
	loadButton.button();
	
	var clearButton = $('#clearButton'); 
	clearButton.button();

	var clientForm = $('#clientForm');

	// right button (SUBMIT)
	rightButton.click(function() {

		clientForm.find('#clientBirthday').datepicker('hide');
		
		// only go through if all form fields are ok
		var allFilled = clientForm.validationEngine('validate');
		
		if (!allFilled)
			return;

		// get the id of the client loaded in the form
		clientId = clientForm.attr('data-id');
		
		// get info about the client
		var clientInfo = {};
		jQuery.each(clientForm.serializeArray(), function(i, field) {
			clientInfo[field.name] = field.value;
		});
		
		// set the clientId in a form hidden field
		clientForm.find('#clientId').val(clientId);

		//console.log('clientInfo from the clientForm',clientInfo);
		
		// if it is a new client ... check if the email is already registered
		if(clientForm.attr('data-id') == 0) {
			
			//console.log('clientInfo: ', clientInfo);
			
			/*
			$.getJSON(window.hotelInfo + "/tmp", {
					email: clientInfo.email
				},
				function(data) {
					if (data.exists) { // client exists
						//console.log(data.msg);
						$('#clientExistsAlert').dialog({
							width:		480,
							height:		200,
							show: 		'fade',
							hide: 		'fade',
							buttons: {
								"Ok": function() {
									$(this).dialog("close");
								}
							}
						});
						return;
					}
					else {
						console.log('criar este cliente');
						loadExtras(schoolId, offerId);
						reservationOptionDialog(clientId, offerId, schoolId,clientInfo);
					}
					//console.log('data from tmp: ', data);
				}
			);
			*/
		}
			
		loadExtras(schoolId, offerId);
		reservationOptionDialog(clientId, offerId, classId, schoolId,clientInfo);
	});

	// leftButton (BACK)
	leftButton.click(function() {
		history.back();
	});
	
	// clearButton
	clearButton.click(function() {
		
		// checkboxes with the client spoken languages 
		var langInputs = $('#clientLanguages li input');
		
		// reset form
        clientForm[0].reset();

        // set id to 0 to indicate there is no data client in the form 
		clientForm.attr('data-id',0);
		
		// clear previous selections
		langInputs.removeAttr('checked');
		
		// pt and en are check by default 
		langInputs.parent().find('input[value=pt],[value=en]').attr('checked','checked');
	});
	
	//loadButton
	loadButton.click(function() {
		
		var langInputs = $('#clientLanguages li input');
		
		$('#clientTableDialog').dialog({
			width:		800,
			height:		500,
			show: 		'fade',
			hide: 		'fade',
			autoOpen:	true,
			modal:		true,
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				},
				"Cancel": 		
				function() {
					
					// reset form
					clientForm[0].reset();
					
					// clear previous language selections
					langInputs.removeAttr('checked');
					
			        // set id to 0 to indicate there is no data client in the form 
					clientForm.attr('data-id',0);
					
					$(this).dialog("close");
				}
			}
			
		});
	});
}


/**
 * load extras associated to the given offer
 * @param schoolId
 * @param offerId
 */
function loadExtras(schoolId, offerId) {

	$.ajax({
		url: 		window.ajaxUrl + '/readExtraAction',
		type:		'POST',
		dataType:	'json',
		data: {
			schoolId:	schoolId,
			offerId:	offerId
		},
		success: 	function(data) {
			
			// unckeck all extras
			var ul = $('#extrasList');
			ul.empty();
			
			// add available extras to checkbox
			for (var i = 0 ; i < data.length ; i++) {
				var li = '<li><input type="checkbox" value="' + data[i].id + '" /><label>' + data[i].name + ' (' + data[i].price + '€) </label></li>';
				$(li).appendTo(ul);
			}
			
			//var list = $('#extrasList li input');
			//list.click(function() {
				//console.log('click');
				//$(this).attr('value','9');
			//});
		},
		error:		function(xhr, status){},
		complete:	function(xhr,status){}
	});
}



function loadLanguages() {
	
	$.ajax({
		url: 		window.ajaxUrl + '/tmp',
		type:		'POST',
		dataType:	'json',
		data: {
			schoolId:	schoolId,
			offerId:	offerId
		},
		success: 	function(data) {
			
		},
		error:		function(xhr, status){},
		complete:	function(xhr,status){}
	});
}




/**
 * choose the reservation options and make the reservation
 */
function reservationOptionDialog(clientId, offerId, classId, schoolId, clientInfo) {

	var clientForm = $('#clientForm');

	$('#reservationOptions').dialog({
		width:		550,
		height:		400,
		show: 		'fade',
		hide: 		'fade',
		autoOpen:	true,
		modal:		true,
		buttons: {
			"Ok": 		
			function() {
				
				// disable the validationEngine
				clientForm.validationEngine('detach');

				// array with extra IDs to be sent to the server
				var arrWithExtrasIDs = [];
				
				// grab all checked fields
				var extras = $('#extrasList li input:checked');
				
				// add IDs to array
				extras.each(function(){
					arrWithExtrasIDs.push($(this).val());
				});
				
				// add extras IDs as a string to the  correspondent hidden field in the clientForm
				clientForm.find('#extrasIDs').val(arrWithExtrasIDs.join('&'));
				
				// ... tranport?
				clientForm.find('#cfTransportField').val($('#reservationOptions').find('#transportOption option:selected').val());
				
				clientForm.find('#offerId').val(offerId);
				clientForm.find('#schoolId').val(schoolId);
				clientForm.find('#classId').val(classId);
				
				// submit all form fields to '/showReservationData'
				clientForm.submit();
				
				$(this).dialog("close");
			},
			"Cancel": 		
			function() {
				
				$(this).dialog("close");
			}
		}
	});
}







/**
 * Config datatable that hold a client list
 */
function datatableConfig() {
	
	// reference to datatable
	var oTable = $('#clientTable').dataTable();
	
	// clientData retrieved from the datatable
	var clientData = null;

	// form with client data
	var clientForm = $('#clientForm'); 
	
	// this attr indicates no client is loaded in the form
	clientForm.attr('data-id',0);

	// buttons
	//var rightButton 	= $('#rightButton'); 
	//var leftButton 		= $('#leftButton'); 

	// datatable click event
	$('#clientTable tbody tr').live('click', function() {
		
		// checkboxes with the client spoken languages 
		var langInputs = $('#clientLanguages li input');
		
		if ( $(this).hasClass('row_selected') ) { // ... a row is selected
			
			// remove the selection
            $(this).removeClass('row_selected'); 

            // reset form
            clientForm[0].reset();
            
			// clear previous language selections
			langInputs.removeAttr('checked');
            
            // set id to 0 to indicate there is no data client in the form 
			clientForm.attr('data-id',0);
        }
        else { // ... no row selected
            
			// avoid multi selected row ... 
            oTable.$('tr.row_selected').removeClass('row_selected');
            
	 		// highlight selected row
            $(this).addClass('row_selected');
            
            //var nTds = $('td', this);
            
	     	// get all client information 
			clientData = oTable.fnGetData(this); 
			
            // set the client id
			clientForm.attr('data-id',clientData.id);
            
			// fill form with all client info
			clientForm.find('#clientName').val(clientData.name);
			clientForm.find('#clientAddress').val(clientData.address);
			clientForm.find('#clientEmail').val(clientData.email);
			clientForm.find('#clientPhone').val(clientData.phone);
			clientForm.find('#clientHeight').val(clientData.height);
			clientForm.find('#clientBirthday').val(clientData.birthday);
			clientForm.find('#clientWeight').val(clientData.weight);
			clientForm.find('#clientSex').val(clientData.sex);
			clientForm.find('#clientNationality').val(clientData.nationality);
			clientForm.find('#clientInfo').val(clientData.info);
			
			// get the languages spoken by the selected client
			$.ajax({
				url: 		window.ajaxUrl + '/clientLanguages',
				type:		'POST',
				dataType:	'json',
				data: {
					clientId:	clientData.id
				},
				success: 	function(data) {
					
					langInputs.removeAttr('checked');
					
					if (data.length!=0) {
						
						// check retrieved languages
						$.each(data, function(key,value){
							var sel = 'input[value=' + value.domain + ']';
							langInputs.parent().find(sel).attr('checked','checked');
						});
					}
				},
				error:		function(xhr, status){},
				complete:	function(xhr,status){}
			});
        }
	});
}







